package com.zeta.demo.seata.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zeta.api.model.DemoDTO;
import com.zeta.demo.seata.dao.DemoSeata2Mapper;
import com.zeta.demo.seata.model.entity.DemoSeata2;
import com.zeta.demo.seata.service.IDemoSeata2Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zetaframework.base.exception.BusinessException;

/**
 * Seata测试2 服务实现类
 *
 * @author AutoGenerator
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DemoSeata2ServiceImpl extends ServiceImpl<DemoSeata2Mapper, DemoSeata2> implements IDemoSeata2Service {


    /**
     * 测试抛异常
     *
     * @param demoDTO demo表数据
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean tryException(DemoDTO demoDTO) {
        // 随机抛异常
        if (RandomUtil.randomBoolean()) {
            throw new BusinessException("随机异常。");
        }

        // 保存数据
        DemoSeata2 entity = BeanUtil.toBean(demoDTO, DemoSeata2.class);
        if (!this.save(entity)) {
            throw new BusinessException("保存失败！！");
        }
        return true;
    }
}
